/**
 * File转换Base64
 */
export const fileToBase64 = function (file) {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.onload = function (event) {
      resolve(event.target.result);
    };
    reader.readAsDataURL(file);
  })
}

/*-------------- 删除相关 START ---------------------*/

/**
 * 根据ID删除
 * @param idType (可选id或bid)
 * @param value
 * @param dataArr arr
 */
export const delById = function ({idType: idType, idValue: value, dataArr: arr}) {
  let _index = findIndexById({idType: idType, idValue: value, dataArr: arr});
  if(_index != -1){
    delItemByIndex({index:_index,dataArr:arr});
  }
}

/**
 * 根据ID删除
 * @param idType (可选id或bid)
 * @param value
 * @param dataArr arr
 */
export const delByIds = function ({idType: idType, idValue: value, dataArr: arr}) {
  let idsArr = value.toString().split(',');
  if(idsArr.length > 0){
    for(var i=0;i<idsArr.length;i++){
      delById({idType:idType,idValue:idsArr[i],dataArr:arr});
    }
  }
}

/**
 * 根据下表删除
 * @param index
 * @param arr
 */
function delItemByIndex({index: index, dataArr: arr}) {
  for (var i = index; i < arr.length; i++) {
    if(i<arr.length -1){
      arr[i] = arr[i+1];
    }else{
      arr.pop();
    }
  }
}

/*-------------- 删除相关 END ---------------------*/

/*-------------- 状态更新相关 START ---------------------*/

/**
 * 更新数据状态
 * @param idType (可选id或bid)
 * @param value
 * @param dataArr arr
 */
export const updateStatusByIds = function ({status: status, idValue: value, dataArr: arr}) {
  let idsArr = value.toString().split(',');
  if(idsArr.length > 0){
    for(var i=0;i<arr.length;i++){
      for(var j=0;j<idsArr.length;j++){
        if(arr[i].id == idsArr[j]){
          arr[i].status = status;
        }
      }
    }
  }
}

/*-------------- 状态更新相关 END ---------------------*/


/**
 * 根据Id进行查找下标
 * @param idType (可选id或bid)
 * @param value
 * @param dataArr arr
 */
function findIndexById({idType: idType, idValue: value, dataArr: arr}) {
  let _index = -1;
  if (idType == 'id') {
    for (var i = 0; i < arr.length; i++) {
      if (value == arr[i].id) {
        _index = i;
        return _index;
      }
    }
  } else if (idType == 'bid') {
    for (var i = 0; i < arr.length; i++) {
      if (value == arr[i].bid) {
        _index = i;
        return _index;
      }
    }
  }
  return _index;
}
